<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>
        <template #right>
          <el-button
            v-allow="import_excel"
            type="warning"
            size="small"
            @click="$router.push('/import')"
          >excel导入</el-button>
          <el-button
            v-allow="export_excel"
            type="danger"
            size="small"
            @click="exportExcel"
          >excel导出</el-button>
          <el-button
            v-allow="add"
            type="primary"
            size="small"
            @click="eAdd"
          >新增员工</el-button>
        </template>
      </page-tools>
      <!-- 表格主体 -->
      <el-card style="margin-top: 10px;">
        <el-table border :data="list" :default-sort="{prop: 'timeOfEntry', order: 'descending'}">
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式">
            <template slot-scope="scope">
              {{ formatEmployment(scope.row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable />
          <el-table-column label="操作" width="280">
            <template slot-scope="scope">
              <el-button
                type="text"
                size="small"
                @click="$router.push(`/employees/detail?id=${scope.row.id}`)"
              >查看</el-button>
              <el-button
                type="text"
                size="small"
                @click="assign(scope.row.id)"
              >分配角色</el-button>
              <el-button
                type="text"
                size="small"
                @click="eDel(scope.row.id)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            :current-page="page"
            :page-sizes="[2, 5, 10, 20]"
            :page-size="size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>
      <!-- 新增弹框 -->
      <el-dialog
        title="新增员工"
        :visible.sync="showDialog"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        @close="hClose"
      >
        <empDialog ref="empDialog" @success="success" />
      </el-dialog>
      <!-- 分配角色 -->
      <el-dialog
        :visible.sync="showPre"
        title="分配角色"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
      >
        <AssignRole ref="assignRole" :cur-id="curId" @close="pClose" />
      </el-dialog>
    </div>
  </div>
</template>
<script>
import { getEmployeesList, delEmployee } from '@/api/employees'
import EmployeeEnum from '@/constant/employees'
import empDialog from './empDialog.vue'
import AssignRole from './assignRole.vue'
// console.log('EmployeeEnum', EmployeeEnum.hireType)
const hireType = {}
EmployeeEnum.hireType.map(item => { hireType[item.id] = item.value })
// console.log(hireType, 'hireType')
export default {
  components: {
    'empDialog': empDialog,
    AssignRole
  },
  data() {
    return {
    // 表格数据
      list: [],
      // 总人数
      total: 0,
      // 页码
      page: 1,
      // 每页条数
      size: 10,
      // 显示弹框
      showDialog: false,
      showPre: false,
      // 当前id
      curId: 0
    }
  },
  created() {
    // 刷新页面
    this.setEmployeesList()
  },
  methods: {
    // 数据转化
    formatEmployment(id) {
      return hireType[id] ? hireType[id] : '未知'
    },
    // 员工列表
    async setEmployeesList() {
      try {
        const res = await getEmployeesList(this.page, this.size)
        // console.log('getEmployeesList', res)
        this.list = res.data.data.rows
        this.total = res.data.data.total
        // 保存数据
      } catch (err) {
        console.log('getEmployeesList', err)
      }
    },
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`)
      this.size = val
      this.setEmployeesList()
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`)
      this.page = val
      this.setEmployeesList()
    },
    // 删除按钮
    eDel(id) {
      // console.log(id)
      this.$confirm('删除该员工, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
        try {
          await delEmployee(id)
          if (this.list.length === 1) {
            this.page--
            if (this.page < 1) {
              this.page = 1
            }
          }
          this.setEmployeesList()
        } catch (error) {
          console.log(error)
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 新增员工按钮，打开弹框
    eAdd() {
      this.showDialog = true
    },
    // 新增成功
    success() {
      this.showDialog = false
      this.total++
      this.page = Math.ceil(this.total / this.size)
      this.setEmployeesList()
    },
    // 关闭弹框后触发
    hClose() {
      this.$refs.empDialog.formReset()
    },
    // 导出事件英文转中文
    exportExcel() {
      import('@/vendor/Export2Excel').then(async excel => {
        const res = await getEmployeesList(this.page, this.size)
        const list = res.data.data.rows
        const { header, data } = this.formatData(list)
        // excel表示导入的模块对象
        // console.log(excel)
        excel.export_json_to_excel({
          header, // 表头 必填
          data, // 具体数据 必填
          filename: 'excel-list', // 文件名称
          autoWidth: true, // 宽度是否自适应
          bookType: 'xlsx' // 生成的文件类型
        })
      })
    },
    // 导出数据转化函数
    formatData(list) {
      const map = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      let header = []

      let data = []
      // 开始代码
      // 找到一个元素
      const one = list[0]
      if (!one) {
        return { header, data }
      }
      header = Object.keys(one).map(key => {
        return map[key]
      })

      // data把list中每一个对象转成 对应的value数组
      data = list.map(obj => {
        // 把  Obj['formOfEmployment']: 1 , 2   ---> '正式'， '非正式'
        const key = obj['formOfEmployment'] // 1, 2
        obj['formOfEmployment'] = hireType[key] ? hireType[key] : '未知'// hireTypEnmu:{1:'正式', '2':'非正式' }

        return Object.values(obj)
      })

      return { header, data }
    },
    assign(id) {
      this.showPre = true
      this.curId = id
      setTimeout(() => {
        this.$refs.assignRole.updateRoleList()
      }, 0)
    },
    // pClose
    pClose() {
      this.showPre = false
      this.setEmployeesList()
    }
  }

}

</script>
